package com.twp.auth.aop.advice;

import com.twp.auth.myexecption.MyException;
import com.twp.common.tuple.ResultDTO;
import org.springframework.http.HttpStatus;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;

/**
 * controller 增强器
 */
@ControllerAdvice
public class MyControllerAdvice {

    /**
     * 应用到所有@RequestMapping注解方法，在其执行之前初始化数据绑定器
     * @param binder
     */
    @InitBinder
    public void initBinder(WebDataBinder binder) {}

    /**
     * 把值绑定到Model中，使全局@RequestMapping可以获取到该值
     * @param model
     */
    @ModelAttribute
    public void addAttributes(Model model) {
        model.addAttribute("author", "tanweiping");
    }

    /**
     * 全局异常捕捉处理
     * @param ex
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = Exception.class)
    public ResultDTO errorHandler(MyException ex) {
        return ResultDTO.builder()
                .isSuccess(false)
                .code(ex.getCode()==null?HttpStatus.INTERNAL_SERVER_ERROR.value():ex.getCode())
                .message(ex.getCause()==null?ex.getMessage():ex.getCause().getMessage())
                .build();
    }

}